#include "CachedTexture.h"

CachedTexture::CachedTexture(TILEDESC1 * td, UINT flag, UINT64 offset)
	:  m_td(td), m_flag(flag), m_offset(offset), m_unloadable(true), m_usageCount(0)
{}
CachedTexture::CachedTexture(ID3D11ShaderResourceView * texture)
	: m_td(nullptr), m_flag(0), m_offset(0), m_unloadable(false), m_usageCount(0)
{
	m_texture.Attach(texture);
}
CachedTexture::CachedTexture(ID3D11ShaderResourceView * texture, bool unloadable)
	: m_td(nullptr), m_flag(0), m_offset(0), m_unloadable(unloadable), m_usageCount(0)
{
	m_texture.Attach(texture);
}
CachedTexture::~CachedTexture() 
{
}
void CachedTexture::Unload()
{
	if (!m_unloadable || m_offset == NOTILE || m_offset == NOTILE64)
		return;
	if (++m_usageCount > 10000)
	{
		m_texture.Release();
		m_td->flags |= m_flag;
	}
}
void CachedTexture::Load(ID3D11ShaderResourceView * texture)
{
	if (!m_unloadable)
		return;
	m_texture.Attach(texture);
	m_td->flags &= ~m_flag;
	m_usageCount = 0;
}
UINT CachedTexture::GetOffset() { return m_offset; }

bool CachedTexture::IsUnloadable() { return m_unloadable; }

ID3D11ShaderResourceView ** CachedTexture::GetTexture()
{
	m_usageCount = 0;
	return &m_texture;
}

bool CachedTexture::IsLoaded() { return (m_texture.p != nullptr); }

void CachedTexture::Init(std::unique_ptr<CachedTexture> & dest, ID3D11ShaderResourceView * tex)
{
	if( tex || (dest && (DWORD)dest->m_offset == NOTILE && dest->m_offset == NOTILE64 ))
	{
		if (dest)
		{
			if (tex)
			{
				dest->Load(tex);
			}
		}
		else
		{
			if (tex)
			{
				dest.reset(new CachedTexture(tex, true));
			}
		}
	}
}
